class ActivityController {
    
    def index = { redirect(action:list,params:params) }

    // the delete, save and update actions only accept POST requests
    static allowedMethods = [delete:'POST', save:'POST', update:'POST']

    def list = {
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
        [ activityInstanceList: Activity.list( params ), activityInstanceTotal: Activity.count() ]
    }

    def show = {
        def activityInstance = Activity.get( params.id )

        if(!activityInstance) {
            flash.message = "${params.name}活動找不到 "
            redirect(action:list)
        }
        else { return [ activityInstance : activityInstance ] }
    }

    def delete = {
        def activityInstance = Activity.get( params.id )
        if(activityInstance) {
            try {
                activityInstance.delete(flush:true)
                flash.message = "${params.name}活動已被刪除"
                redirect(action:list)
            }
            catch(org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "Activity ${params.id} could not be deleted"
                redirect(action:show,id:params.id)
            }
        }
        else {
            flash.message = "Activity not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def edit = {
        def activityInstance = Activity.get( params.id )

        if(!activityInstance) {
            flash.message = "Activity not found with id ${params.id}"
            redirect(action:list)
        }
        else {
            return [ activityInstance : activityInstance ]
        }
    }

    def update = {
        def activityInstance = Activity.get( params.id )
        if(activityInstance) {
            if(params.version) {
                def version = params.version.toLong()
                if(activityInstance.version > version) {
                    
                    activityInstance.errors.rejectValue("version", "activity.optimistic.locking.failure", "Another user has updated this Activity while you were editing.")
                    render(view:'edit',model:[activityInstance:activityInstance])
                    return
                }
            }
            activityInstance.properties = params
            if(!activityInstance.hasErrors() && activityInstance.save()) {
                flash.message = "Activity ${params.id} updated"
                redirect(action:show,id:activityInstance.id)
            }
            else {
                render(view:'edit',model:[activityInstance:activityInstance])
            }
        }
        else {
            flash.message = "Activity not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def create = {
        def activityInstance = new Activity()
        activityInstance.properties = params
        return ['activityInstance':activityInstance]
    }

    def save = {
        def activityInstance = new Activity(params)
        if(!activityInstance.hasErrors() && activityInstance.save()) {
            flash.message = "活動 ${activityInstance.name} created"
            redirect(action:show,id:activityInstance.id)
        }
        else {
            render(view:'create',model:[activityInstance:activityInstance])
        }
    }
    
    //-------------------------------------------------
    
    def select = {
    	 params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
         [ activityList: Activity.list( params ), activityTotal: Activity.count(), type:params.type ]
    }
    
    def register = {
    	def activity = Activity.get(params.id)
    	def registeredCount = 0
    	activity.records.each { record ->
    		if (record.status == Status.REGISTERED.toString()) {
    			registeredCount++
    		}
    	}
    	[activity:activity, registeredCount:registeredCount]
    }
    
    def registerSubmit = {
    	def activity = Activity.get(params.id)
    	def person = Person.get(params.person.id)
    	def record = Record.findByActivityAndPerson(activity, person)
    	
    	def originalRegisterDate = record.registerDate
    	record.registerDate = new Date()
    	if (record.status == Status.NONREGISTERED.toString()){
    		record.status = Status.REGISTERED.toString()
    		flash.message = person.name + '已經在 ' + record.registerDate + '報到成功'
    	} else if (record.status == Status.REGISTERED.toString() || record.status == Status.OTHER.toString()) {
    		flash.message = '覆蓋 ' + person.name + '記錄，原來 '+ originalRegisterDate + '變成' + record.registerDate
    	}
    	
    	if(record.save()){
    		redirect(action:register,params:[id:params.id])
    	}
    }
    
    def done = {
    	def activity = Activity.get(params.id)
    	def doneCount = 0
    	activity.records.each { record ->
    		if (record.status == Status.DONE.toString()) {
    			doneCount++
    		}
    	}
    	[activity:activity, doneCount:doneCount]
    }
    
    def doneSubmit = {
    	def activity = Activity.get(params.id)
    	def person = Person.get(params.person.id)
    	def record = Record.findByActivityAndPerson(activity, person)
    	
    	def originalDoneDate = record.doneDate
    	record.doneDate = new Date()
    	if (record.registerDate.getYear() > 70) {
    		record.period = record.doneDate.getTime() - record.registerDate.getTime()
    	}
    	if (record.status == Status.NONREGISTERED.toString() || record.status == Status.REGISTERED.toString()) {
    		record.status = Status.DONE.toString()
    		flash.message = person.name + '已經在 ' + record.doneDate + '簽退成功'
    	} else if (record.status == Status.OTHER.toString()) {
    		record.status = Status.OTHERDONE.toString()
    		flash.message = person.name + '已經在 ' + record.doneDate + '簽退成功'
    	} else if (record.status == Status.DONE.toString()) {
    		flash.message = '覆蓋 ' + person.name + '記錄，原來 '+ originalDoneDate + '變成' + record.doneDate
    	}
    	
    	if(record.save()){
    		redirect(action:done,params:[id:params.id])
    	}
    }
    
    def registerCoverDialog = {
    	def record = Record.get(params.recordId)
    	[record:record]
    }
    
    def doneCoverDialog = {
    	def record = Record.get(params.recordId)
    	[record:record]
    }
    
    def registerExceptDialog = {
    	def person = Person.get(params.personId)
    	[person:person, activityId:params.activityId]
    }
    
    def registerCoverDialogSubmit = {
    	def record = Record.get(params.record.id)
    	def originalRegisterDate = record.registerDate
    	record.registerDate = new Date()
    	if(record.save()){
    		flash.message = '覆蓋 ' + record.person.name + '記錄，原來 '+ originalRegisterDate + '變成' + record.registerDate
    		redirect(action:register, params:[id:record.activity.id])
    	}
    }
    def doneCoverDialogSubmit = {
    	def record = Record.get(params.record.id)
    	def originalRegisterDate = record.registerDate
    	record.registerDate = new Date()
    	if(record.save()){
    		flash.message = '覆蓋 ' + record.person.name + '記錄，原來 '+ originalRegisterDate + '變成' + record.registerDate
    		redirect(action:done, params:[id:record.activity.id])
    	}
    }
    
    def registerExceptDialogSubmit = {
    	def activity = Activity.get(params.activityId)
    	def person = Person.get(params.personId)
    	def record = new Record([person:person, activity:activity])
    		record.status = Status.OTHER.toString()
    	if (record.save()) {
    		redirect(action:register,params:[id:activity.id])
    	}
    }
    
    def uidSubmit = {
    	def activity = Activity.get(params.id)
    	def person = Person.findByUid(params.uid)
    	if (!person) {
    		flash.message = ' 無此人 '
    		redirect(action:register, params:[id:params.id])
    	}
    	def record = Record.findByActivityAndPerson(activity, person)
    	if (record) {
	    	if (record.status == Status.NONREGISTERED.toString()){
	    		record.status = Status.REGISTERED.toString()
	    		record.registerDate = new Date()
	    		if (record.save()) {
	    			flash.message = person.name + '已經在 ' + record.registerDate + '報到成功'
	    		}	    			
	    	} else if (record.status == Status.REGISTERED.toString() || record.status == Status.OTHER.toString()) {
	    		flash.message = person.name + '已經報到，確定覆蓋記錄？'
	    		redirect(action:registerCoverDialog, params:[recordId:record.id])
	    	}
    	} else {
    		flash.message = person.name + '不是應出席人員，確定報到？ '
    		redirect(action:registerExceptDialog, params:[personId:person.id, activityId:activity.id])
    	}
    	
    	redirect(action:register,params:[id:params.id])
    }
    
    def uidDoneSubmit = {
    	def activity = Activity.get(params.id)
    	def person = Person.findByUid(params.uid)
    	if (!person) {
    		flash.message = ' 無此人 '
    		redirect(action:register, params:[id:params.id])
    	}
    	def record = Record.findByActivityAndPerson(activity, person)
    	if (record) {
	    	if (record.status == Status.NONREGISTERED.toString() || record.status == Status.REGISTERED.toString() || record.status == Status.OTHER.toString()){
	    		record.status = Status.DONE.toString()
	    		record.doneDate = new Date()
	    		if (record.registerDate.getYear() > 70) {
	        		record.period = record.doneDate.getTime() - record.registerDate.getTime()
	        	}
	    		if (record.save()) {
	    			flash.message = person.name + '已經在 ' + record.registerDate + '簽退成功'
	    		}	    
	    	} else if (record.status == Status.DONE.toString() || record.status == Status.OTHERDONE.toString()) {
	    		flash.message = person.name + '已經簽退，確定覆蓋記錄？'
	    		redirect(action:doneCoverDialog, params:[recordId:record.id])
	    	}
    	} else {
    		flash.message = person.name + '非應出席人員'
    	}
    	redirect(action:done,params:[id:params.id])
    }
}
